/**
 * NetworkManager.java
 *
 * @version 1.0
 * @author nicky.han
 */
package cn.etgps.etgps.manager;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

import cn.etgps.etgps.utils.Constant;

/**
 * Manage the network.
 *
 * @author nicky.han
 */
public class NetworkManager {
    /**
     * Use to set the time out when connect to server
     */
    private static final int TIME_OUT_VALUE = 6000;

    private static HttpURLConnection mURLConnection = null;


    /**
     * get data from server
     *
     * @param path the URL address
     * @return string result
     */
    public static synchronized String getDataFromServer(String path) {
        String result = "";
        InputStream is = null;
        BufferedReader br = null;
        try {
            mURLConnection = (HttpURLConnection) (new URL(path)).openConnection();
            mURLConnection.setConnectTimeout(TIME_OUT_VALUE);
            if (mURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                is = mURLConnection.getInputStream();
                br = new BufferedReader(new InputStreamReader(is, "utf-8"));
                int i = -1;
                char[] ch = new char[4096];
                StringBuffer sb = new StringBuffer();
                while ((i = br.read(ch)) != -1) {
                    sb.append(new String(ch, 0, i));
                }
                result = sb.toString();
                is.close();
                br.close();
            } else {
                result = Constant.CONNECT_TO_SERVER_FAILED;
            }
        } catch (Exception e) {
            e.printStackTrace();
            result = Constant.CONNECT_TO_SERVER_FAILED;
        } finally {
            try {
                mURLConnection.disconnect();
                if (is != null) {
                    is.close();
                }
                if (br != null) {
                    br.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * post data from server
     *
     * @param path the URL address
     * @return string result
     */
    public static synchronized String postDataToServer(String path, Map<String, String> nameValuePairs) {
        String result = "";
        InputStream is = null;
        BufferedReader br = null;
        StringBuffer postContent = null;
        try {
            mURLConnection = (HttpURLConnection) (new URL(path)).openConnection();
            mURLConnection.setConnectTimeout(TIME_OUT_VALUE);
            mURLConnection.setDoInput(true);
            mURLConnection.setDoOutput(true);
            mURLConnection.setRequestMethod("POST");
            mURLConnection.setUseCaches(false);
            mURLConnection.setInstanceFollowRedirects(false);
            mURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            mURLConnection.connect();
            if (nameValuePairs != null) {
                int addIndex = 0;
                postContent = new StringBuffer();
                for (Map.Entry<String, String> entry : nameValuePairs.entrySet()) {
                    ;
                    if (addIndex > 0) {
                        postContent.append("&");
                    }
                    postContent.append(entry.getKey());
                    postContent.append("=");
                    postContent.append(entry.getValue());
                    addIndex++;
                }

                mURLConnection.getOutputStream().write(postContent.toString().getBytes());// 输入参数
            }
            if (mURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                is = mURLConnection.getInputStream();
                br = new BufferedReader(new InputStreamReader(is, "utf-8"));

                String readLine = null;
                while ((readLine = br.readLine()) != null) {
                    result = result + readLine;
                }
                is.close();
                br.close();
            } else {
                result = Constant.CONNECT_TO_SERVER_FAILED;
            }
        } catch (Exception e) {
            e.printStackTrace();
            result = Constant.CONNECT_TO_SERVER_FAILED;
        } finally {
            mURLConnection.disconnect();
            try {
                if (is != null) {
                    is.close();
                }
                if (br != null) {
                    br.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }
}
